package main

import (
	//register"cossbow.com/ms/consul"
	register "cossbow.com/ms/etcdv3"
	"cossbow.com/ms/rpc"
	. "cossbow.com/ms/util"
	"flag"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"syscall"
)

const (
	svcName = "test/hello"
)

func main() {
	var name string
	flag.StringVar(&name, "name", "", "name of server")
	flag.Parse()
	if "" == name {
		flag.Usage()
		return
	}

	li, er := net.Listen("tcp4", ":0")
	ThrowException(er)
	defer li.Close()
	//tcpAddr := li.Addr().(*net.TCPAddr)
	addr := li.Addr().String()
	fmt.Println("listen: ", addr)

	server := grpc.NewServer()
	service := &rpc.GreeterServerImpl{Name: name}
	rpc.RegisterGreeterServer(server, service)

	//register := consul.NewConsulRegister("127.0.0.1:8500", 5)
	//regInfo := consul.RegisterInfo{
	//	Port:           tcpAddr.Port,
	//	Host:           tcpAddr.IP.String(),
	//	ServiceName:    svcName,
	//	UpdateInterval: 5,
	//}
	//er = register.Register(regInfo)
	er = register.Register("127.0.0.1:2379", svcName, addr, 5)
	ThrowException(er)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)
	go func() {
		s := <-ch
		register.DeRegister(svcName, addr)
		//register.DeRegister(regInfo)

		if i, ok := s.(syscall.Signal); ok {
			os.Exit(int(i))
		} else {
			os.Exit(0)
		}

	}()

	er = server.Serve(li)
	ThrowException(er)
}
